{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "ename": "RuntimeError",
     "evalue": "asyncio.run() cannot be called from a running event loop",
     "output_type": "error",
     "traceback": [
      "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[1;31mRuntimeError\u001b[0m                              Traceback (most recent call last)",
      "\u001b[1;32m<ipython-input-1-b06dd880a610>\u001b[0m in \u001b[0;36m<module>\u001b[1;34m\u001b[0m\n\u001b[0;32m     35\u001b[0m \u001b[1;32mif\u001b[0m \u001b[0m__name__\u001b[0m \u001b[1;33m==\u001b[0m \u001b[1;34m'__main__'\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m     36\u001b[0m     \u001b[1;31m# 协程函数最终还是要通过事件循环来调用\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m---> 37\u001b[1;33m     \u001b[0masyncio\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mrun\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mmain\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m\u001b[0;32m     38\u001b[0m \u001b[1;33m\u001b[0m\u001b[0m\n",
      "\u001b[1;32me:\\Python37\\lib\\asyncio\\runners.py\u001b[0m in \u001b[0;36mrun\u001b[1;34m(main, debug)\u001b[0m\n\u001b[0;32m     32\u001b[0m     \u001b[1;32mif\u001b[0m \u001b[0mevents\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0m_get_running_loop\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;33m)\u001b[0m \u001b[1;32mis\u001b[0m \u001b[1;32mnot\u001b[0m \u001b[1;32mNone\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m     33\u001b[0m         raise RuntimeError(\n\u001b[1;32m---> 34\u001b[1;33m             \"asyncio.run() cannot be called from a running event loop\")\n\u001b[0m\u001b[0;32m     35\u001b[0m \u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m     36\u001b[0m     \u001b[1;32mif\u001b[0m \u001b[1;32mnot\u001b[0m \u001b[0mcoroutines\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0miscoroutine\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mmain\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n",
      "\u001b[1;31mRuntimeError\u001b[0m: asyncio.run() cannot be called from a running event loop"
     ]
    }
   ],
   "source": [
    "import asyncio\n",
    "import time\n",
    "\n",
    "# async定义一个协程函数\n",
    "async def testa(x):\n",
    "    print(\"in test a\")\n",
    "    await asyncio.sleep(3)\n",
    "    print(\"Resuming a\")\n",
    "    return x\n",
    "\n",
    "\n",
    "async def testb(x):\n",
    "    print(\"in test b\")\n",
    "    await asyncio.sleep(1)\n",
    "    print('Resuming b')\n",
    "    return x\n",
    "\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "ename": "RuntimeError",
     "evalue": "asyncio.run() cannot be called from a running event loop",
     "output_type": "error",
     "traceback": [
      "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[1;31mRuntimeError\u001b[0m                              Traceback (most recent call last)",
      "\u001b[1;32m<ipython-input-2-16830916c679>\u001b[0m in \u001b[0;36m<module>\u001b[1;34m\u001b[0m\n\u001b[0;32m     17\u001b[0m \u001b[1;32mif\u001b[0m \u001b[0m__name__\u001b[0m \u001b[1;33m==\u001b[0m \u001b[1;34m'__main__'\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m     18\u001b[0m     \u001b[1;31m# 协程函数最终还是要通过事件循环来调用\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m---> 19\u001b[1;33m     \u001b[0masyncio\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mrun\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mmain\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m",
      "\u001b[1;32me:\\Python37\\lib\\asyncio\\runners.py\u001b[0m in \u001b[0;36mrun\u001b[1;34m(main, debug)\u001b[0m\n\u001b[0;32m     32\u001b[0m     \u001b[1;32mif\u001b[0m \u001b[0mevents\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0m_get_running_loop\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;33m)\u001b[0m \u001b[1;32mis\u001b[0m \u001b[1;32mnot\u001b[0m \u001b[1;32mNone\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m     33\u001b[0m         raise RuntimeError(\n\u001b[1;32m---> 34\u001b[1;33m             \"asyncio.run() cannot be called from a running event loop\")\n\u001b[0m\u001b[0;32m     35\u001b[0m \u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m     36\u001b[0m     \u001b[1;32mif\u001b[0m \u001b[1;32mnot\u001b[0m \u001b[0mcoroutines\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0miscoroutine\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mmain\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n",
      "\u001b[1;31mRuntimeError\u001b[0m: asyncio.run() cannot be called from a running event loop"
     ]
    }
   ],
   "source": [
    "\n",
    "# 串行执行\n",
    "# await只有在协程函数中使用\n",
    "async def main():\n",
    "    start = time.time()\n",
    "    resulta = await testa(1)\n",
    "    resultb = await testb(2)\n",
    "    print(\"test a result is %d\"%resulta)\n",
    "    print(\"test b result is %d\"%resultb)\n",
    "    print(\"use %s time\"%(time.time()-start))\n",
    "\n",
    "\n",
    "# if __name__ == '__main__':\n",
    "#     # 协程函数最终还是要通过事件循环来调用\n",
    "#     loop = asyncio.get_event_loop()\n",
    "#     loop.run_until_complete(main())\n",
    "\n",
    "if __name__ == '__main__':\n",
    "    # 协程函数最终还是要通过事件循环来调用\n",
    "    asyncio.run(main())\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 通过gather实现并发执行\n",
    "async def main():\n",
    "    start = time.time()\n",
    "    resulta,resultb = await asyncio.gather(testa(1),testb(2))\n",
    "    print(\"test a result is %d\" % resulta)\n",
    "    print(\"test b result is %d\" % resultb)\n",
    "    print(\"use %s time\" % (time.time() - start))\n",
    "\n",
    "if __name__ == '__main__':\n",
    "    loop = asyncio.get_event_loop()\n",
    "    loop.run_until_complete(main())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 使用asyncio.ensure_future封装为task实现并发执行\n",
    "async def main():\n",
    "    start = time.time()\n",
    "\n",
    "    taska = asyncio.ensure_future(testa(1))\n",
    "    taskb = asyncio.ensure_future(testb(2))\n",
    "\n",
    "    print(taska)\n",
    "    print(taskb)\n",
    "    print(taska.done(), taskb.done())\n",
    "    await taskb\n",
    "    await taska\n",
    "    print(taska.done(), taskb.done())\n",
    "\n",
    "    print(taskb.result())\n",
    "    print(taska.result())\n",
    "    print(\"use %s time\" % (time.time() - start))\n",
    "\n",
    "if __name__ == '__main__':\n",
    "    loop = asyncio.get_event_loop()\n",
    "    loop.run_until_complete(main())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 创建task对象2：使用loop.create_task() 方法\n",
    "async def main():\n",
    "    start = time.time()\n",
    "\n",
    "    taska = loop.create_task(testa(1))\n",
    "    taskb = loop.create_task(testb(2))\n",
    "\n",
    "    print(taska)\n",
    "    print(taskb)\n",
    "    print(taska.done(), taskb.done())\n",
    "    await taskb\n",
    "    await taska\n",
    "    print(taska.done(), taskb.done())\n",
    "\n",
    "    print(taskb.result())\n",
    "    print(taska.result())\n",
    "    print(\"use %s time\" % (time.time() - start))\n",
    "\n",
    "if __name__ == '__main__':\n",
    "    loop = asyncio.get_event_loop()\n",
    "    loop.run_until_complete(main())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 与asyncio.gather 类似的还有一个 asyncio.wait,参数为协程函数list\n",
    "async def main():\n",
    "    start = time.time()\n",
    "    done,pending = await asyncio.wait([testa(1),testb(2)])\n",
    "    print(list(done))\n",
    "    print(list(pending))\n",
    "    print(list(done)[0].result())\n",
    "    print(\"use %s time\" % (time.time() - start))\n",
    "\n",
    "if __name__ == '__main__':\n",
    "    loop = asyncio.get_event_loop()\n",
    "    loop.run_until_complete(main())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 测试asyncio.wait自定义返回时机\n",
    "async def testa(x):\n",
    "    print(\"in test a\")\n",
    "\n",
    "    await asyncio.sleep(3)\n",
    "    print(1/0)\n",
    "    print(\"Resuming a\")\n",
    "    return x\n",
    "\n",
    "\n",
    "async def testb(x):\n",
    "    print(\"in test b\")\n",
    "    await asyncio.sleep(1)\n",
    "    print(1/0)\n",
    "    print('Resuming b')\n",
    "    return x\n",
    "\n",
    "\n",
    "async def main():\n",
    "    start = time.time()\n",
    "    done,pending = await asyncio.wait([testa(1),testb(2)],return_when=asyncio.tasks.FIRST_EXCEPTION)\n",
    "    print('done', list(done))\n",
    "    print('pending', list(pending))\n",
    "    print(\"use %s time\" % (time.time() - start))\n",
    "\n",
    "if __name__ == '__main__':\n",
    "    loop = asyncio.get_event_loop()\n",
    "    loop.run_until_complete(main())\n",
    "    loop.run_forever()"
   ]
  }
 ],
 "metadata": {
  "interpreter": {
   "hash": "0d97df724f9992bec51a1ba2c335179ff7e7085e5d5d4df7f317912701d4af90"
  },
  "kernelspec": {
   "display_name": "Python 3.7.3 64-bit (system)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.3"
  },
  "orig_nbformat": 4
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
